package com.chlitina.store.modules.cash.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.utils.StoreCareUtils;
import com.chlitina.store.common.utils.Utils;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.Customer;
import com.chlitina.store.modules.base.entity.CustomerEmployeeRelationship;
import com.chlitina.store.modules.base.entity.StoreCardTemplateDuration;
import com.chlitina.store.modules.base.entity.StoreCardTemplateTimes;
import com.chlitina.store.modules.base.entity.StoreCare;
import com.chlitina.store.modules.base.service.CustomerEmployeeRelationshipService;
import com.chlitina.store.modules.base.service.CustomerService;
import com.chlitina.store.modules.base.service.StoreCareService;
import com.chlitina.store.modules.base.service.StoreProductService;
import com.chlitina.store.modules.cash.dao.StoreCardDurationDao;
import com.chlitina.store.modules.cash.dao.StoreCardTimesDao;
import com.chlitina.store.modules.cash.entity.StoreCardAll;
import com.chlitina.store.modules.cash.entity.StoreCardDuration;
import com.chlitina.store.modules.cash.entity.StoreCardProduct;
import com.chlitina.store.modules.cash.entity.StoreCardTimes;
import com.chlitina.store.modules.cash.entity.StoreConsume;
import com.chlitina.store.modules.cash.model.CustomerInfo;
import com.chlitina.store.modules.cash.model.CustomerQuery;
import com.chlitina.store.modules.cash.model.Member;
import com.chlitina.store.modules.cash.model.MemberConsumeDetail;
import com.chlitina.store.modules.cash.model.MemberShoppingCart;
import com.chlitina.store.modules.cash.model.SolutionStoreCareCart;
import com.chlitina.store.modules.cash.model.StoreCareCart;
import com.chlitina.store.modules.cash.service.MemberService;
import com.chlitina.store.modules.cash.service.NomemberService;
import com.chlitina.store.modules.cash.service.StoreConsumeService;
import com.chlitina.store.modules.employee.dao.EmployeeDao;
import com.chlitina.store.modules.employee.entity.Employee;
import com.chlitina.store.modules.expert.entity.Care;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * Crash Controller
 * 
 * @author Songsong.xu
 * @version 2013-3-23
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH + "/cash/member")
public class MemberController extends BaseController {
	@Autowired
	private StoreConsumeService storeConsumeService;
	@Autowired
	private CustomerEmployeeRelationshipService customerEmployeeRelationshipService;
	@Autowired
	private StoreCardTimesDao storeCardTimesDao;
	@Autowired
	private StoreCardDurationDao storeCardDurationDao;

	@Autowired
	private NomemberService nomemberService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private StoreCareService storeCareService;
	@Autowired
	private StoreProductService storeProductService;
	@Autowired
	private CustomerService customerService;
	static int TAB_ID_CARDS_TIMES = 0;
	static int TAB_ID_CARDS_DURATION = 1;
	static int TAB_ID_CARDS_PRODUCT = 2;
	static int TAB_ID_CARDS_ALL = 3;

	static int TAB_ID_NEWCARDS_PAYMENT_ALLCARD = 0;
	static int TAB_ID_NEWCARDS_PAYMENT_CASH = 1;

	static int TAB_ID_PRODUCT_PAYMENT_PRODUCTCARD = 0;
	static int TAB_ID_PRODUCT_PAYMENT_ALLCARD = 1;
	static int TAB_ID_PRODUCT_PAYMENT_CASH = 2;

	static int TAB_ID_PAYMENT_NEWCARDS = 0;
	static int TAB_ID_PAYMENT_RECHARGE = 1;
	static int TAB_ID_PAYMENT_PRODUCT = 2;

	public static String MEMBER_URL = "redirect:" + Global.ADMIN_PATH
			+ "/cash/member";

	public static interface KEY {
		String KEY_MEMBER = "member";
		String KEY_TAB_ACTIVE = "tabActive";
		String KEY_MESSAGE = "message";
	}

	public static interface URI {
		String URI_MEMBER_CONSUME = "modules/cash/cashMemberConsume";
		String URI_MEMBER_DETAIL = "modules/cash/cashMemberDetail";
		String URI_MEMBER_SHOPPING_DETAIL = "modules/cash/shoppingDetail";
		String URI_MEMBER_SHOPPING_DETAIL_DOCARE = "modules/cash/shoppingDetailDocare";
		String URI_MEMBER_SHOPPING_DETAIL_PRODUCT = "modules/cash/shoppingDetailProduct";
		String URI_MEMBER_SHOPPING_DETAIL_RECHARGE = "modules/cash/shoppingDetailRecharge";
		String URI_MEMBER_SHOPPING_PAYMENT = "modules/cash/shoppingPayment";
		String URI_MEMBER_CARDS = "modules/cash/cashMemberCards";
		String URI_MEMBER_SHOPPING_NEWCARDS = "modules/cash/cashMemberShoppingNewCards";
		String URI_MEMBER_BUY_PRODUCT = "modules/cash/cashMemberBuyProduct";
		String URI_MEMBER_DO_CARE = "modules/cash/memberDoCare";
		String URI_MEMBER_DO_SOLUTION_CARE = "modules/cash/memberDoSolutionCare";
		String URI_MEMVER_SHOOPING_NEWCARDS_PAYMENT = "modules/cash/newcardsPayment";
		String URI_MEMVER_SHOOPING_PRODUCT_PAYMENT = "modules/cash/productPayment";
		String URI_MEMVER_SHOOPING_RECHARGE_PAYMENT = "modules/cash/rechargePayment";

		String URI_MEMBER_INFO = "modules/cash/memberInfo";
		String URI_MEMBER_CARDS_INFO = "modules/cash/memberCards";
		String URI_MEMBER_HISTORY_CONSUME_LIST = "modules/cash/memberHistoryConsumeList";
		String URI_MEMBER_HISTORY_CONSUME_DETAILS = "modules/cash/memberHistoryConsumeDetail";

	}

	@RequestMapping(value = { "query", "" })
	public String listMembers(CustomerQuery customerQuery,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Member member = getMember();
		if (member != null && !member.getMenuState().isEmptyShopping()) {
			return URI.URI_MEMBER_DETAIL;
		}

		model.addAttribute("customerQuery", customerQuery);
		Page<Customer> page = customerService.find(new Page<Customer>(request,
				response), customerQuery.getSearchType() + "", customerQuery
				.getKeyWords());
		List<CustomerInfo> result = new ArrayList<CustomerInfo>();
		List<Customer> list = page.getList();
		List<Long> added = new ArrayList<Long>();
		for (Customer c : list) {
			CustomerInfo in = new CustomerInfo();
			in.setCustomer(c);
			added.clear();
			List<StoreConsume> findByCustomer = storeConsumeService
					.findByCustomer(c.getId());
			if (!findByCustomer.isEmpty()) {
				in.setLastComingDate(findByCustomer.get(0).getConsume_Time());
			} else {
				in.setLastComingDate(new Date());
			}

			List<CustomerEmployeeRelationship> ship = customerEmployeeRelationshipService
					.findByCustomer(c.getId());
			for (CustomerEmployeeRelationship p : ship) {
				in.getEmployees().add(p.getEmployee());
			}
			List<StoreCardTimes> timesCard = storeCardTimesDao
					.findListByCustomer(StoreUtils.getStore().getId(),
							c.getId());
			List<StoreCardDuration> durationCard = storeCardDurationDao
					.findListByCustomer(StoreUtils.getStore().getId(),
							c.getId());
			List<StoreCare> cares = in.getCares();
			for (StoreCardDuration storeCardDuration : durationCard) {
				StoreCardTemplateDuration template = storeCardDuration
						.getTemplate();
				StoreCare storeCare = template.getStoreCare();
				if (StoreCareUtils.getStatus(storeCare) == Care.FLAG_DISABLE) {
					continue;
				}
				if (storeCardDuration.getEndTime().before(new Date())) {
					continue;
				}
				if (!Utils.contains(added, storeCare.getId())) {
					cares.add(template.getStoreCare());
					added.add(template.getStoreCare().getId());
				}
			}

			for (StoreCardTimes storeCardTimes : timesCard) {
				StoreCardTemplateTimes template = storeCardTimes.getTemplate();
				StoreCare storeCare = template.getStoreCare();
				if (StoreCareUtils.getStatus(storeCare) == Care.FLAG_DISABLE) {
					continue;
				}
				if (storeCardTimes.getRemainTimes() < 1) {
					continue;
				}
				if (!Utils.contains(added, storeCare.getId())) {
					cares.add(template.getStoreCare());
					added.add(template.getStoreCare().getId());
				}
			}
			result.add(in);
		}

		Page<CustomerInfo> cP = new Page<CustomerInfo>(page.getPageNo(),
				page.getPageSize(), page.getCount(), result);
		model.addAttribute("page", cP);
		return URI.URI_MEMBER_CONSUME;
	}

	@ResponseBody
	@RequestMapping(value = "carddetails")
	public String carddetails(HttpServletRequest request,
			HttpServletResponse response, String cardType, String cardID) {
		response.setContentType("application/json; charset=UTF-8");
		List<Map<String, String>> list = Lists.newArrayList();
		long cID = 0;
		Class clazz = null;
		if ("times".equals(cardType)) {
			clazz = StoreCardTimes.class;
		} else if ("duration".equals(cardType)) {
			clazz = StoreCardDuration.class;
		} else if ("product".equals(cardType)) {
			clazz = StoreCardProduct.class;
		} else if ("all".equals(cardType)) {
			clazz = StoreCardAll.class;
		} else {
			// unsupported card type
		}
		try {
			cID = Long.parseLong(cardID);
		} catch (NumberFormatException e) {
			// wrong cardID, bad request
			e.printStackTrace();
		}
		String findConsumeByCard = storeConsumeService.findConsumeByCard(clazz,
				cID);
		System.err.println(findConsumeByCard);

		return findConsumeByCard;
	}

	@RequestMapping(value = "historyConsumeList")
	public String consume(HttpServletRequest request,
			HttpServletResponse response, Customer customer, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return listMembers(new CustomerQuery(), request, response, model);
		}
		Page<StoreConsume> page = new Page<StoreConsume>(request, response);
		page.updatePage(member.getHistoryConsumes());
		model.addAttribute("page", page);
		return URI.URI_MEMBER_HISTORY_CONSUME_LIST;
	}

	@RequestMapping(value = "dropShopping")
	public String dropShopping(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		StoreUtils.removeMember();
		request.getSession().removeAttribute(KEY.KEY_MEMBER);
		return listMembers(new CustomerQuery(), request, response, model);
	}

	@RequestMapping(value = "historyConsumeDetail")
	public String consumeDetail(@RequestParam("consumeId") String consumeId,
			HttpServletRequest request, Model model) {
		MemberConsumeDetail consumeInfo = memberService
				.loadMemberConsumeInfo(consumeId);
		model.addAttribute("consumeInfo", consumeInfo);
		return "modules/base/customerConsumeDetail";
	}

	@RequestMapping(value = { "detail" })
	public String memberDetail(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String parameter = request.getParameter("id");
		int id = 0;
		try {
			id = Integer.parseInt(parameter);
		} catch (NumberFormatException e) {
			return listMembers(new CustomerQuery(), request, response, model);
		}
		Member member = getMember();
		boolean create = false;
		if (member == null) {
			create = true;
		} else {
			if (member.getCustomer().getId().longValue() != id) {
				create = true;
			}
		}
		if (create) {
			member = new Member();
			Customer customer = customerService.get(new Long(id));
			member.setCustomer(customer);
			memberService.loadingMemberInfo(member);
			StoreUtils.setMember(member);
			request.getSession().setAttribute(KEY.KEY_MEMBER, member);
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		return URI.URI_MEMBER_DETAIL;
	}

	Member getMember() {
		return StoreUtils.getMember();
	}

	String getDiretctURL(String uri) {
		return MEMBER_URL + "/" + uri;
	}

	@RequestMapping(value = { "info", "cards" })
	public String memberInfo(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		return URI.URI_MEMBER_INFO;
	}

	@RequestMapping(value = { "cardsInfo" })
	public String memberCardsInfo(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		return URI.URI_MEMBER_CARDS_INFO;
	}

	@RequestMapping(value = { "care" })
	public String care(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return listMembers(new CustomerQuery(), request, response, model);
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		model.addAttribute("systemCare", new StoreCareCart());
		member.setAllcareList(this.getCares(member));
		member.setCardCareList(member.findAllCardCare());
		return URI.URI_MEMBER_DO_CARE;
	}
	
	@RequestMapping(value = { "solutionCare" })
	public String solutionCare(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return listMembers(new CustomerQuery(), request, response, model);
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		model.addAttribute("systemCare", new SolutionStoreCareCart());
		member.setAllcareList(this.getCares(member));
		member.setCardCareList(member.findAllCardCare());
		return URI.URI_MEMBER_DO_SOLUTION_CARE;
	}


	@RequestMapping(value = { "care/add" })
	public String addCare(StoreCareCart careCart, Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes, Model model) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return listMembers(new CustomerQuery(), request, response, model);
		}
		MemberShoppingCart shoppingCart = member.getShoppingCart();
		careCart.setStoreCare(storeCareService.get(careCart.getStoreCare()
				.getId()));
		careCart.setEmployee(employeeDao
				.findOne(careCart.getEmployee().getId()));

		model.addAttribute(KEY.KEY_MEMBER, member);
		model.addAttribute("systemCare", new StoreCareCart());
		shoppingCart.doSystemCare(careCart);
		addMessage(redirectAttributes, "添加成功");
		return getDiretctURL("care");
	}

	@RequestMapping(value = { "care/delete" })
	public String deleteCare2(FocusEvent focusEvent, Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes, Model model) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return listMembers(new CustomerQuery(), request, response, model);
		}
		MemberShoppingCart shoppingCart = member.getShoppingCart();
		String parameter = request.getParameter("id");
		if (parameter != null && !parameter.isEmpty()) {
			int id = Integer.parseInt(parameter);
			shoppingCart.deleteStoreCareCartByCartId(
					shoppingCart.getSystemCares(), id);
			addMessage(redirectAttributes, "删除成功");
		}
		model.addAttribute("systemCare", new StoreCareCart());
		member.updateMenuState();
		return URI.URI_MEMBER_DO_CARE;
	}

	@ResponseBody
	@RequestMapping(value = { "verifyCode" })
	public String verifyCode() {
		Member member = getMember();
		if (member == null) {
			return "";
		}
		MemberShoppingCart shoppingCart = member.getShoppingCart();
		return shoppingCart.getStoreConsume().getVerify_Code();
	}

	public List<StoreCare> getCares(Member member) {
		List<StoreCare> storeCares = nomemberService.findStoreCares();
		MemberShoppingCart shoppingCart = (MemberShoppingCart) member
				.getShoppingCart();
		List<Long> added = new ArrayList<Long>();
		if (shoppingCart != null) {
			List<StoreCareCart> systemCares = shoppingCart.getSystemCares();
			for (StoreCareCart cart : systemCares) {
				added.add(cart.getStoreCare().getId());
			}
		}
		return storeCares;
	}

	@ResponseBody
	@RequestMapping(value = "loadingEmployees")
	public String treeCardCareDatas(HttpServletRequest request,
			HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		Set<Map<String, Object>> set = Sets.newHashSet();
		List<Employee> employees = employeeDao.findListByStore(StoreUtils
				.getStore().getId(),Employee.STATUS_WORKING);
		if (employees != null) {
			for (Employee employee : employees) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", employee.getId().longValue());
				map.put("name", employee.getName());
				set.add(map);
			}
		}
		return JsonMapper.getInstance().toJson(set);
	}
}
